package team.star.werespos.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.base.Preconditions;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import team.star.werespos.config.shiro.CurrPrincipal;
import team.star.werespos.exception.GlobalException;
import team.star.werespos.mapper.PermissionRoleMapper;
import team.star.werespos.mapper.RoleMapper;
import team.star.werespos.model.entity.Permission;
import team.star.werespos.model.entity.PermissionRole;
import team.star.werespos.model.entity.Role;
import team.star.werespos.model.enums.CodeMsgEnum;
import team.star.werespos.service.RoleService;

import java.util.List;
import java.util.Optional;
import java.util.Set;

/**
 * RoleServiceImpl class<br/>
 *
 * @author CAI
 * @since 2019/04/09
 */
@Slf4j
@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private PermissionRoleMapper permissionRoleMapper;

    @Override
    public Role getOne(Integer rid) {
        return roleMapper.getRole(rid);
    }

    @Override
    public void insertOne(Role role) {
        // 非空检查
        Preconditions.checkNotNull(role, "role is null!");
        // 新增
        Integer result = roleMapper.insert(role);
        if (result == 0) {
            log.error("【新增角色】失败！result = [{}], role = [{}]", result, role);
            throw GlobalException.create(CodeMsgEnum.DATABASE_EXCEPTION);
        }
        Set<Permission> permissions = role.getPermissions();
        if (!CollectionUtils.isEmpty(permissions)) {
            PermissionRole permissionRole = new PermissionRole();
            permissionRole.setRid(role.getRid());
            permissions.forEach(permission -> permissionRoleMapper.insert(
                    permissionRole.setPid(permission.getPid())
            ));
        }
    }

    @Override
    public List<Role> listRole() {
        return roleMapper.listRoles();
    }

    @Override
    public void updateById(Role role) {
        Integer result = roleMapper.updateById(role);
        if (result == 0) {
            log.error("【修改角色】失败！result = [{}], role = [{}]", result, role);
            throw GlobalException.create(CodeMsgEnum.DATABASE_EXCEPTION);
        }
        Role roleFromDb = getOne(role.getRid());
        Set<Permission> permissionsFromDB = roleFromDb.getPermissions();
        Set<Permission> permissions = role.getPermissions();
        // 没更改权限则结束执行
        if (permissionsFromDB.equals(permissions)) {
            return;
        }
        // 不能修改当前用户拥有的角色的权限
        if (CurrPrincipal.get().getRoles().contains(role)) {
            throw GlobalException.create(CodeMsgEnum.INVALID_OPERATION);
        }
        permissionsFromDB.forEach(p -> permissionRoleMapper.delete(new QueryWrapper<PermissionRole>()
                            .eq("rid", role.getRid())
                            .eq("pid", p.getPid()))
        );
        permissions.forEach(p -> permissionRoleMapper.insert(
                new PermissionRole(p.getPid(), role.getRid()))
        );
    }

    @Override
    public void deleteById(Role role) {
        Set<Role> roles = CurrPrincipal.get().getRoles();
        // 不能删除当前用户拥有的角色
        if (roles.contains(role)) {
            throw GlobalException.create(CodeMsgEnum.INVALID_OPERATION);
        }
        Optional.ofNullable(roleMapper.deleteById(role))
                .ifPresent(result -> {
                    if (result == 0) {
                        log.error("【删除角色】失败！result = [{}], role = [{}]", result, role);
                        throw GlobalException.create(CodeMsgEnum.DATABASE_EXCEPTION);
                    }
                });
    }



}

